package com.hengtiansoft.lfy.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.adapter.EvaluatorAdapter;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.entity.EvaluatorMessageEntity;
import com.hengtiansoft.lfy.entity.EvaluatorModeEntity;
import com.hengtiansoft.lfy.entity.EvaluatorRankings;
import com.hengtiansoft.lfy.entity.xfutil.Result;
import com.hengtiansoft.lfy.entity.xfutil.Word;
import com.hengtiansoft.lfy.net.NetHelper;
import com.hengtiansoft.lfy.net.NetUtils;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.EvaParser;
import com.hengtiansoft.lfy.utils.Kdxf_TTSPlayer;
import com.hengtiansoft.lfy.utils.XFEvaluatorManager;
import com.hengtiansoft.lfy.utils.XmlResultParser;
import com.hengtiansoft.lfy.widget.TranslateDialog;
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SynthesizerListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ztspeech.constant.ZTConstant;
import com.ztspeech.translator.ZTTranslator;
import com.ztspeech.translator.interf.ZTTranslatorListener;

import java.util.ArrayList;
import java.util.List;


/**
 *
 * Created by suyiyang on 2016/11/4.
 */

public class ExerciseHistoryActivity extends BaseActivity{

    private ListView lv_content;
    private ImageView iv_image;
    private TextView tv_modeName;
    private ImageView iv_back;
    private EvaluatorAdapter evaluatorAdapter;
    //每个MODE下的详细信息
    private ArrayList<EvaluatorMessageEntity> evList ;
    //mode信息
    private EvaluatorModeEntity modeEntity;

    //当前跟读的语音路径
    private String voicePath;
    /**
     * 当前操作的item
     */
    private int currPos = 0;
    /**
     * 当前试题的item
     */
    private ProgressDialog mPd;
    /**
     * 需要单个翻译的单词
     */
    private String word;
    /**
     * 练习时长
     */
    private long exTime = 0;

    private DisplayImageOptions defaultOptions;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise);
        initData();
    }

    /**
     * 初始化
     */
    private void initData() {

        Bundle bundle = getIntent().getBundleExtra("bundle");
        modeEntity = (EvaluatorModeEntity) bundle.getSerializable("mode");

        lv_content = (ListView) findViewById(R.id.lv_content);
        iv_image = (ImageView) findViewById(R.id.iv_pager_image);
        tv_modeName = (TextView) findViewById(R.id.tv_modename);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        XFEvaluatorManager.getKdxfInstance().initEvaluator(this);

        getEvaluator();

        evaluatorAdapter = new EvaluatorAdapter(this,evList,listener);
        lv_content.setAdapter(evaluatorAdapter);
        lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(currPos != position){
                    clear();
                    evaluatorAdapter.setAutoPlay(false);
                }
                currPos = position;
                evaluatorAdapter.setCurrentPosition(position);
            }
        });
        //设置翻译服务器地址
        ZTTranslator.getTranslatorInstance().setServerAddr(Constants.TRANSLATE);
        mPd = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        mPd.setCanceledOnTouchOutside(false);
        mPd.setMessage(getString(R.string.is_translating));

        defaultOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.ARGB_8888)
                .build();
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clear();
                ExerciseHistoryActivity.this.finish();
            }
        });

    }
    /**
     * 显示数据
     */
    private void showViewData() {
        iv_image.setImageResource(R.drawable.img_disney);
        tv_modeName.setText(modeEntity.getName());
        String url = Constants.SERVER_HOST +"/images/"+ modeEntity.getImagePath();
        ImageLoader.getInstance().displayImage(url, iv_image, defaultOptions);
        if(lv_content.getFooterViewsCount()>0)
            return;
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.todayscore,null);
        TextView tv = (TextView) v.findViewById(R.id.tv_todayscore);
        tv.setText(getString(R.string.finishscore));
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 需要登陆判断接口
                if(Config.isUserLogined()) {
                    int score = 0;
                    if(evList != null){
                        for(int i = 0;i < evList.size(); i ++){
                            String code = evList.get(i).getScore();
                            if(TextUtils.isEmpty(code)){
                                Toast.makeText(ExerciseHistoryActivity.this,getString(R.string.finishallexercise),Toast.LENGTH_SHORT).show();
                                return;
                            }
                            score += Integer.parseInt(code);
                        }
                        score /= evList.size();
                    }
                    Log.d("tag","evList = "+evList.toString());
                    Log.d("tag","score = "+score);
                    Bundle bundle = new Bundle();
//                    bundle.putParcelableArrayList("list",evList);
                    bundle.putSerializable("list",evList);

                    Intent intent = new Intent(ExerciseHistoryActivity.this, TodayScoreDialogActivity.class);
                    intent.putExtra("score",score);
                    intent.putExtra("bundle",bundle);
                    startActivity(intent);
                }
                else{
                    startActivity(new Intent(ExerciseHistoryActivity.this, LoginActivityV2.class)
                            .putExtra("from", "toCollectionActivity"));
                    Toast.makeText(ExerciseHistoryActivity.this,  getString(R.string.not_login_title), Toast.LENGTH_LONG)
                            .show();
                }

            }
        });
        lv_content.addFooterView(v);
    }

    /**
     * 获取每个试题的具体内容
     */
    private synchronized void  getEvaluator(){
        evList = new ArrayList<>();
        if(modeEntity == null) {
            return;
        }
//        evList = EvaluatorDBManager.getInstance().getEvaluatorMessage(modeEntity.getSerial());
//        if(evList != null && evList.size() > 0){
//            if(evaluatorAdapter != null)
//                evaluatorAdapter.refreshModeData(evList);
//            return;
//        }
        int id = Integer.parseInt(modeEntity.getSerial());
        NetHelper.getEvaluator(this, id, new NetUtils.NetCallBack<List<EvaluatorMessageEntity>>() {
            @Override
            public void success(List<EvaluatorMessageEntity> rspData) {
                Log.d("tag","rspData = "+rspData);
                evList = (ArrayList<EvaluatorMessageEntity>) rspData;
                showViewData();
                getFinish();
            }
            @Override
            public void failed(String msg) {

            }
        });
    }

    /**
     * 获取已完成内容的信息
     */
    private void getFinish(){

        NetHelper.getCompleteItem(this, modeEntity.getSerial(), new NetUtils.NetCallBack<String>() {
            @Override
            public void success(String rspData) {
                Log.d("tag","rspData = "+rspData);
                EvaParser.getInstance().parseScoreJson(rspData,evList);
                evaluatorAdapter.refreshModeData(evList);
            }

            @Override
            public void failed(String msg) {

            }
        });
    }



    /**
     * 与adapter交互
     */
    private EvaluatorAdapter.EvaluatorAdapterListener listener = new EvaluatorAdapter.EvaluatorAdapterListener() {
        @Override
        public void speak(String str) {
            exTime = System.currentTimeMillis();
            voicePath = Environment.getExternalStorageDirectory()+"/lfy/evaluator/"+"lfy"+System.currentTimeMillis() +".wav";
            int x = XFEvaluatorManager.getKdxfInstance().startEvaluator(str,mEvaluatorListener,voicePath);

        }

        @Override
        public void playEnglish(String english) {
            Kdxf_TTSPlayer.getInstense().setExternalTtsListener(mTtsListener);
            Kdxf_TTSPlayer.getInstense().TTSPlay(english,"","");
        }

        @Override
        public void playVoice(String path) {
            Kdxf_TTSPlayer.getInstense().setExternalTtsListener(mTtsListener);
            Kdxf_TTSPlayer.getInstense().TTSPlayOpu(path, "");
        }

        @Override
        public void stopspeak() {
            XFEvaluatorManager.getKdxfInstance().stopEvaluating();
        }

        @Override
        public void stopEnglish() {
            Kdxf_TTSPlayer.getInstense().stopTTs();
            Kdxf_TTSPlayer.getInstense().setExternalTtsListener(null);
        }

        @Override
        public void stopVoice() {
            Kdxf_TTSPlayer.getInstense().stop();
            Kdxf_TTSPlayer.getInstense().setExternalTtsListener(null);
        }

        @Override
        public void transWord(String string) {
            //翻译单词
            if(!"".equals(string.trim())){
                word = string;
                ZTTranslator.getTranslatorInstance().setLanguage(ZTConstant.HTTP_LANGUAGE_ENCH);
                ZTTranslator.getTranslatorInstance().translate(mTranLisenter,string);
                //进度条
                mPd.show();
            }
        }

        @Override
        public void clickItem(int pos) {
            if(currPos != pos){
                clear();
                evaluatorAdapter.setAutoPlay(true);
            }
            currPos = pos;
            evaluatorAdapter.setCurrentPosition(pos);
        }

        @Override
        public void clearWorking() {
            clear();
        }
    };
    /**
     * 合成回调
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {
        @Override
        public void onSpeakBegin() {

        }

        @Override
        public void onBufferProgress(int i, int i1, int i2, String s) {

        }

        @Override
        public void onSpeakPaused() {

        }

        @Override
        public void onSpeakResumed() {

        }

        @Override
        public void onSpeakProgress(int i, int i1, int i2) {

        }

        @Override
        public void onCompleted(SpeechError speechError) {
            if(speechError != null)
                Toast.makeText(ExerciseHistoryActivity.this,getString(R.string.network_error),Toast.LENGTH_SHORT).show();
            if(evaluatorAdapter != null)
                evaluatorAdapter.resetImageResource();
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };

    /**
     * 紫冬翻译回调接口
     */
    private ZTTranslatorListener mTranLisenter = new ZTTranslatorListener() {
        @Override
        public void onResult(String text) {
            if(mPd != null && mPd.isShowing()){
                mPd.dismiss();
            }
            new TranslateDialog.Builder(ExerciseHistoryActivity.this,word,text).create().show();
        }

        @Override
        public void onError(int i) {
            if(mPd != null && mPd.isShowing()){
                mPd.dismiss();
            }
            Toast.makeText(ExerciseHistoryActivity.this,getString(R.string.network_error),Toast.LENGTH_SHORT).show();
            Log.d("tag", "翻译错误,错误码:" + i);
        }
    };

    // 评测监听接口
    private EvaluatorListener mEvaluatorListener = new EvaluatorListener() {

        @Override
        public void onResult(EvaluatorResult evaluatorResult, boolean isLast) {
            if(evaluatorAdapter != null)
                evaluatorAdapter.resetImageResource();
            if (isLast) {
                XmlResultParser resultParser = new XmlResultParser();
                Result result = resultParser.parse(evaluatorResult.getResultString());

                if (null != result) {
                    ArrayList<Word> words = result.sentences.get(0).words;
                    StringBuffer sb = new StringBuffer();
                    for(int i = 0; i < words.size();i ++){
                        //音节内容(sil、silv 表示静音，fil 表示噪音)
                        String str = words.get(i).content;
                        if(!"sil".equals(str) && !"silv".equals(str) && !"fil".equals(str)) {
                            words.get(i).total_score = Math.round(words.get(i).total_score * 20);
                            sb.append((int)(words.get(i).total_score)+" ");
                        }
                    }
                    //更新数据
                    evList.get(currPos).setScore(Math.round(result.total_score * 20)+"");
                    evList.get(currPos).setState(1+"");
                    evList.get(currPos).setLocalVoicePath(voicePath);
                    //获取多颜色文本
                    evList.get(currPos).setWordscore(sb.toString());
                    evaluatorAdapter.notifyDataSetChanged();
                    //更新数据库
                    // TODO: 2016/9/28
//                    EvaluatorDBManager.getInstance().updateEvaluator(evList.get(currPos));
//                    //更新练习时长
//                    EvaluatorDBManager.getInstance().updateExerciseTime(modeEntity.getSerial(),exTime);

                    uploadTime();
                } else {

                }
            }
        }

        @Override
        public void onError(SpeechError error) {
            if(evaluatorAdapter != null)
                evaluatorAdapter.resetImageResource();
            Toast.makeText(ExerciseHistoryActivity.this,getString(R.string.network_error),Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onBeginOfSpeech() {
            // 此回调表示：sdk内部录音机已经准备好了，用户可以开始语音输入
        }
        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            exTime = System.currentTimeMillis() - exTime;
        }
        @Override
        public void onVolumeChanged(int volume, byte[] data) {
//            showTip("当前音量：" + volume);
        }
        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }

    };

    @Override
    public void onPause() {
        super.onPause();
        clear();
    }

    /**
     * 清理可能存在的任务
     */
    private void clear(){
        XFEvaluatorManager.getKdxfInstance().cancelEvaluating();
        Kdxf_TTSPlayer.getInstense().stopTTs();
        Kdxf_TTSPlayer.getInstense().stop();
        Kdxf_TTSPlayer.getInstense().setExternalTtsListener(null);
        if(evaluatorAdapter != null){
            evaluatorAdapter.resetImageResource();
        }
    }

    /**
     * 实时上传练习时间
     */
    private void uploadTime() {
        if (!Config.isUserLogined()) {
            return;
        }
        int time = (int) (exTime / 1000);
        if (time > 0 && time < 10 * 60) {
            Log.d("tag","todaytime = "+time);
            NetHelper.uploadExerciseTime(this, time+"", new NetUtils.NetCallBack<EvaluatorRankings>() {
                @Override
                public void success(EvaluatorRankings rspData) {
                    Log.d("tag","uploadExerciseTime success");
                }

                @Override
                public void failed(String msg) {
                    Log.d("tag", "failed");
                }
            });
        }
    }
}
